#include "SocketIO.h"
#include <algorithm>
#include <iostream>
using std::endl; using std::cout;

void ReadQueue::pushData(string &s)
{
    queue_.push(std::move(s));
}

uint16_t ReadQueue::readHeadSize(char *buffer)
{
    uint16_t *ret = (uint16_t*)buffer;
    return *ret;
}

void ReadQueue::reset_un()
{
	un_.header_ = 0;
	un_.read_ = -2;
	un_.pack_.resize(0);
}

void ReadQueue::pushMore(char *buffer, uint16_t len)
{
    if (1 == len)
    {
        un_.read_ = -1;
        un_.header_ = *buffer;
        return ;
    }

    uint16_t packLen = readHeadSize(buffer);
    buffer += 2;
    len -= 2;
    if (packLen > len)
    {
        un_.read_ = len;
		un_.header_ = packLen;
		un_.pack_.append(buffer, len);
        //memcpy(un_.pack_.buffer_, buffer, len);
        return;
    }
	string s(buffer, packLen);
    pushData(s);
    buffer += packLen;
    len -= packLen;
    if (len > 0)
    {
        pushMore(buffer, len);
    }

    return;
}

SocketIO::SocketIO()
{}

void SocketIO::filterData(char *buffer, uint16_t len)
{
    if (-2 == readQueue_.un_.read_)
    {
        readQueue_.pushMore(buffer, len);
    }
    else
    {
        if (-1 == readQueue_.un_.read_)
        {
            uint16_t hight = (uint16_t)(*buffer);
           // readQueue_.un_.pack_.len_ = readQueue_.un_.header_ | (hight << 8);
            readQueue_.un_.header_ = readQueue_.un_.header_ | (hight << 8);
            readQueue_.un_.read_ = 0;
            buffer += 1;
            len -= 1;
        }
        uint16_t need = readQueue_.un_.header_ - readQueue_.un_.read_;
        if (need > len)
        {
            //memcpy(readQueue_.un_.pack_.buffer_ + readQueue_.un_.read_, buffer, len);
	    	readQueue_.un_.pack_.append(buffer, len);
            readQueue_.un_.read_ += len;
            return;
        }
	    else
	    {
	    	readQueue_.un_.pack_.append(buffer, need);
	    	readQueue_.un_.read_ += need;
	    }
        readQueue_.pushData(readQueue_.un_.pack_);
        readQueue_.reset_un();

        buffer += need;
        len -= need;
        if (0 == len)
        {
            return;
        }
        readQueue_.pushMore(buffer, len);
        return;
    }
    
    return;
}

